package com.fdb.efp.cus.service.util;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 征信文件下载  
 * @author tzy
 * 2018-05-05
 */
public class HttpUp   {   
	protected static Logger logger = LoggerFactory.getLogger(HttpUp.class);
	  @SuppressWarnings({ "unused", "static-access" })
	public String downloadFileByUrl(String srcUrl,String filePath,int reqCount) {
		  HttpClient httpclient = new HttpClient();
		  GetMethod httpget = new GetMethod(srcUrl);
		  FileOutputStream out = null;
		  String flag = "1";
		  try {
			  String[] array = srcUrl.split("\\/");
			  String[] fname = array[array.length-1].split("\\.");
			  String fileName = "";
			  String extName = "";
			  if (fname.length == 2) {
				  fileName = fname[0];
				  extName = fname[1];
			  }
			  File filedir = new File(filePath);
			  if(!filedir.exists()) {
				  filedir.mkdirs();
			  }
			  File wdFile = new File(filePath,fileName+"."+extName);
			  out  = new FileOutputStream(wdFile);
			  int status = httpclient.executeMethod(httpget);
			  if (status == HttpStatus.SC_OK) {
				  flag = "0";
				  InputStream instream = httpget.getResponseBodyAsStream();
				  int l;
				  byte[] tmp = new byte[2048];
				  while ((l = instream.read(tmp)) != -1) {
					  out.write(tmp,0,l);
				  }
				  instream.close();
			  }
			  
			  out.flush();
		  } catch (Exception e) {
			  logger.error("文件下载失败!",e);
		  } finally {
			  httpget.releaseConnection();
			  reqCount = 0;
			  try {
				  if (out!=null) {
					  out.close();
				  }
			  } catch (Exception e) {
				  logger.error("文件下载失败!",e);
			  }
		  }
		  
		  return flag;
	  }
	  
	  /**
		 * 获取响应数据
		 * @param in
		 * @param len
		 * @return
		 * @throws IOException
		 */
		public static byte[] readContent(InputStream in, int len) throws IOException {
			if (len <= 0) {
				byte[] buf = new byte[2048];
				byte[] readBuf = new byte[1024];
				int totalLen = 0;
				while (true) {
					int readLen = in.read(readBuf);
					if (readLen <= 0) {
						break;
					}
					if (totalLen + readLen > buf.length) {
						byte[] tmp = new byte[buf.length + readLen + 1024];
						System.arraycopy(buf, 0, tmp, 0, totalLen);
						buf = tmp;
					}
					System.arraycopy(readBuf, 0, buf, totalLen, readLen);
					totalLen += readLen;
				}

				byte[] retBuf = new byte[totalLen];
				System.arraycopy(buf, 0, retBuf, 0, totalLen);
				return retBuf;
			}

			int totalLen = 0;
			byte[] buf = new byte[len];
			while (totalLen < len) {
				int readLen = in.read(buf, totalLen, len - totalLen);
				if (readLen <= 0) {
					break;
				}
				totalLen += readLen;
			}

			return buf;
		}
	  

}  
